package com.qiaoba.auth.controller;

import com.qiaoba.api.auth.entity.LoginUser;
import com.qiaoba.api.auth.entity.dto.LoginDTO;
import com.qiaoba.auth.service.SysLoginService;
import com.qiaoba.common.base.context.UserInfoContext;
import com.qiaoba.common.base.entity.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录 Web层
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/5/5 9:43
 */
@Tag(name = "1.登陆管理")
@RestController
@RequiredArgsConstructor
public class SysLoginController {

    private final SysLoginService sysLoginService;
    private final UserDetailsService userDetailsService;

    @Operation(summary = "1_获取验证码")
    @GetMapping("/captchaImage")
    public AjaxResult getCaptchaImage() {
        AjaxResult result = AjaxResult.success();
        result.putAll(sysLoginService.getCaptchaImage());
        return result;
    }

    @Operation(summary = "2_登陆")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginDTO dto) {
        String token = sysLoginService.login(dto);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("token", token);
        return ajax;
    }

    @Operation(summary = "3_获取登陆用户的信息")
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = (LoginUser) userDetailsService.loadUserByUsername(UserInfoContext.getUsername());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("permissions", loginUser.getPermissions());
        ajax.put("roles", loginUser.getRoles());
        ajax.put("user", loginUser);
        return ajax;
    }

    @Operation(summary = "4_获取登陆用户的路由")
    @GetMapping("/getRouters")
    public AjaxResult getRouters() {
        return AjaxResult.success(sysLoginService.selectRoutersByUserId(UserInfoContext.getUserId()));
    }

}
